package hanhns.test.addNote;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import hanhns.test.R;
import hanhns.test.broadcastReceiver.Receiver;
import hanhns.test.provider_database.BNoteProvider;
import hanhns.test.service.PlaymusicService;

public class NewNoteUseContenProvider extends Activity{
	
	private static final String TAG = "NewNoteUseContenProvider";
	
	// cac cot trong bang
	private static final String[] COLUMNS = new String[] {
        BNoteProvider._ID_COLUMN, // 0
        BNoteProvider.NOTE_TITLE_COLUMN, // 1
        BNoteProvider.NOTE_CONTENT_COLUMN  // 2
	};
	
	// chi so cua cac cot trong bang
	private static final int COLUMN_INDEX_TITLE = 1;
	private static final int COLUMN_INDEX_CONTENT = 2;
	  
	private Uri mUri;
    private Cursor mCursor;
    private EditText mTitleNote;
    private EditText mContentNote;
    private NotificationManager mNotify;
    private PlaymusicService mPlay;;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //xoa notify cho note moi
        final Intent intent = getIntent();
        int note_id = intent.getIntExtra(Receiver.key, -10);
        mNotify = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
        if (note_id != -10) {
        	mNotify.cancel(note_id);
        }
        
        mPlay = new PlaymusicService();
        mPlay.test();
        
//        private ServiceConnection Connect = new ServiceConnection() {
//			
//			@Override
//			public void onServiceDisconnected(ComponentName arg0) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void onServiceConnected(ComponentName arg0, IBinder arg1) {
//				// TODO Auto-generated method stub
//				
//			}
//		}; 
        

        //lay lai chuoi action cua intent
        final String action = intent.getAction();
        Log.e(TAG, action);
        
        if (Intent.ACTION_EDIT.equals(action) || Intent.ACTION_VIEW.equals(action)) {
            // Requested to edit or view: set that state, and the data being edited.
            mUri = intent.getData();
            mCursor = managedQuery(mUri, COLUMNS, null, null, null);
        }else if (Intent.ACTION_INSERT.equals(action)) {
            // Requested to insert: set that state, and create a new entry
            // in the container.
//            mUri = getContentResolver().insert(intent.getData(), null);
        	mCursor = null;
        }else {
            // Whoops, unknown action!  Bail.
            Log.e(TAG, "Unknown action, exiting");
            finish();
            return;
        }

        setContentView(R.layout.new_note);
        
        // The text view for our note, identified by its ID in the XML file.
        mTitleNote = (EditText) findViewById(R.id.title);
        mContentNote = (EditText) findViewById(R.id.content);

        // Get the note!
//        mCursor = managedQuery(mUri, COLUMNS, null, null, null);
        
        final Button b = (Button) findViewById(R.id.save_button);
        b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String getUser = mTitleNote.getText().toString();
	            String getPass = mContentNote.getText().toString();
	            int length = getUser.length();
	            if (length > 0) {
	            	ContentValues values = new ContentValues();
	                values.put(BNoteProvider.NOTE_TITLE_COLUMN, getUser);
	                values.put(BNoteProvider.NOTE_CONTENT_COLUMN, getPass);
	                if ( getIntent().getAction().equals(Intent.ACTION_INSERT )){
	                	Uri newNoteUri = getContentResolver().insert(BNoteProvider.CONTENT_URI, values);
	                	Log.e(TAG, "insert success new note with uri: " + newNoteUri);
		                Intent intent = new Intent(NewNoteUseContenProvider.this, Receiver.class);
		                intent.setData(newNoteUri);
		                sendBroadcast(intent);
	                } else {
	                	int count = getContentResolver().update(mUri, values, null, null);
	                	Log.e(TAG, "update success note for uri: " + mUri);
	                }	                
	               finish();
	            } else {
	            	showalert();
	            }
				
			}
		});
	}
	
	//thiet lap lai su lieu khi chay Activity nay
	@Override
    protected void onResume() {
        super.onResume();
        
        //play music in background
        startService(new Intent(this, PlaymusicService.class));
        
        // If we didn't have any trouble retrieving the data, it is now
        // time to get at the stuff.
        if (mCursor != null) {
            // Make sure we are at the one and only row in the cursor.
            mCursor.moveToFirst();

            // This is a little tricky: we may be resumed after previously being
            // paused/stopped.  We want to put the new text in the text view,
            // but leave the user where they were (retain the cursor position
            // etc).  This version of setText does that for us.
            String title = mCursor.getString(COLUMN_INDEX_TITLE);
            mTitleNote.setTextKeepState(title);
            String content = mCursor.getString(COLUMN_INDEX_CONTENT);
            mContentNote.setTextKeepState(content);

        }else {
        	mTitleNote.setText("");
        	mContentNote.setText("");
        }
    }
	
	// goi tu dong de save lai du lieu khi nhan phim back / home
	 @Override
	    protected void onPause() {
	        super.onPause();
	        //stop play music in background
	        stopService(new Intent(this, PlaymusicService.class));
	        mPlay.test();
	        
	        InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(mContentNote.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(mTitleNote.getWindowToken(), 0);			
	    }
	 
	 private void showalert() {
		 mPlay.pauseMusic();
		 
		 AlertDialog.Builder alert = new AlertDialog.Builder(this);
     	alert.setMessage("You have't entered title for new note. Do you want to cancel creat new note?")
     	.setTitle("Warning")
     	.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				mPlay.resume();
			}
		})
     	.setPositiveButton("YES", new DialogInterface.OnClickListener() {
     	public void onClick(DialogInterface dialog, int id) {
     	//  Action for 'NO' Button
     		finish();
     	}
     	});
     	alert.show();
	 }
	 
}
